

package com.hgx.springcloud.paymenthystrix.service.impl;

import com.hgx.springcloud.paymenthystrix.dao.PaymentMapper;
import com.hgx.springcloud.paymenthystrix.entities.Payment;
import com.hgx.springcloud.paymenthystrix.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class PaymentServiceImpl implements PaymentService {


    @Override
    public String ok(String id) {
        return "线程：" + Thread.currentThread().getName() + "\t" + "payment ok ,id:" + id;
    }

    @Override
    @HystrixCommand(fallbackMethod = "timeOutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    public String timeOut(String id) {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程：" + Thread.currentThread().getName() + "\t" + "payment time out ,id:" + id;
    }

    private String timeOutHandler(String id) {
        return "线程：" + Thread.currentThread().getName() + "\t" + "系统繁忙 payment time out handler ,id:" + id;
    }


    @HystrixCommand(fallbackMethod = "circuitBreakerFallBack", commandProperties = {
            //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
            //请求次数
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            //时间窗口期
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
            //失败率达到多少后跳闸
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "20")

    })
    @Override
    public String circuitBreaker(String id) {
        if ("1".equals(id)) {
            throw new RuntimeException("oooooo");
        }
        return Thread.currentThread().getName() + "\t ok ok " + UUID.randomUUID();
    }

    public String circuitBreakerFallBack(String id) {
        return "circuitBreakerFallBack。。。。。。。。";
    }

}
